﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;

namespace DBUtility
{
    /// <summary>
    /// BaseConfiguration
    /// 连接配置。
    /// 
    /// 修改纪录
    /// 
    ///		2008.06.08 版本：3.5 JiRiGaLa 将读取配置文件进行分离。
    ///		2008.05.08 版本：3.4 JiRiGaLa 获得不同的数据库连接字符串 OracleConnection、SqlConnection、OleDbConnection。
    ///		2007.11.28 版本：3.2 JiRiGaLa 获得数据连接字符串，减少配置文件的读的次序，提高性能。
    ///		2007.05.23 版本：3.1 JiRiGaLa 增加 public const string 定义部分。
    ///		2007.04.14 版本：3.0 JiRiGaLa 检查程序格式通过，不再进行修改主键操作。
    ///		2006.11.17 版本：2.4 JiRiGaLa GetFromRegistryKey() 方法主键进行整理，删除多余的引用。
    ///		2006.05.02 版本：2.3 JiRiGaLa GetFromConfig 增加从配置文件读取数据库联接的方法。
    ///		2006.04.18 版本：2.2 JiRiGaLa 重新调整主键的规范化。
    ///		2006.02.02 版本：2.0 JiRiGaLa 删除数据库连接池的想法，修改了命名，更规范化，贴切了。 
    ///		2005.12.29 版本：1.0 JiRiGaLa 从配置文件读取数据库连接。
    /// 
    /// 版本：3.5
    /// 
    /// <author>
    ///		<name>JiRiGaLa</name>
    ///		<date>2008.06.08</date>
    /// </author> 
    /// </summary>
    public class BaseConfiguration
    {
        private static BaseConfiguration instance;
        private static object locker = new Object();

        public static BaseConfiguration Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (locker)
                    {
                        if (instance == null)
                        {
                            instance = new BaseConfiguration();
                        }
                    }
                }
                return instance;
            }
        }

        public string CustomerCompanyName = string.Empty;				        // 客户公司的全名
        public ConfigurationCategory ConfigurationFrom = ConfigurationCategory.UserConfig; // RegistryKey、Configuration、UserConfig 注册表或者配置文件读取参数
        public string SoftName = string.Empty;				        // 当前软件ID
        public string SoftFullName = string.Empty;                     // 软件的名称
        public RunMode RunMode = RunMode.Local;                    // Local、WebService、Remoting 连接方式
        public string RootMenuId = string.Empty;				        // 根菜单主键
        public string CurrentLanguage = "zh-CHS";                         // 当前客户选择的语言
        public string Version = "1.0";                            // 当前版本

        // 这里是服务器设置项
        public string CommonWebService = string.Empty;   // 通用服务器地址
        public string WebService = string.Empty;   // 远程服务器地址

        public string FileWebService = string.Empty;   // 文件服务器地址
        public string WorkReportWebService = string.Empty;   // 工作日志服务器地址

        public string WebServiceUsername = COMPANY_NAME;   // WebService用户名
        public string WebServicePassword = COMPANY_NAME;   // WebService密码

        /// <summary>
        /// 启用分级管理范围权限设置
        /// </summary>
        public bool UsePermissionScope = false;

        /// <summary>
        /// 启用逐级授权
        /// </summary>
        public bool UseLicensedPermission = false;

        /// <summary>
        /// 模块菜单权限
        /// </summary>
        public bool UseModulePermission = false;

        /// <summary>
        /// 是否采用了数据表的列权限
        /// </summary>
        public bool UseTableColumnsPermission = false;

        // 数据库连接
        public DataBaseType DataBaseType = DataBaseType.Sqlserver;   // 数据库类别
        public string ServerName = string.Empty;             // 服务器名称
        public string DataBase = string.Empty;             // 连接的数据库名称
        public bool TrustLink = true;                     // 是否为信任的连接
        public string Username = string.Empty;             // 用户名
        public string Password = string.Empty;             // 用户密码
        public int MaxPoolSize = 1;                        // 数据库连接池最大打开数
        public int MinPoolSize = 1;                        // 数据库连接池最小打开数
        public string RegisterKey = string.Empty;             // 注册码

        public string StartupPath = string.Empty;             // 当前网站的安装地址

        public string UserCenterDbConnection = string.Empty;             // 数据库连接的字符串
        public string BusinessDbConnection = string.Empty;             // 业务数据库

        public string ServiceFactory = "ServiceFactory";
        public string ServicePath = "DotNet.Service";
        public string DbHelperClass = "DotNet.DbUtilities.SqlHelper";
        public string DbHelperAssmely = "DotNet.DbUtilities";
        public bool RecordLog = true;

        public string LoginAssembly = "DotNet.WinForm.Login";
        public string LoginForm = "FrmLogin";
        public string MainForm = "MainForm";

        public bool LoadUser = true;
        public bool AllowUserRegister = true;

        public string RegisterException = "请您联系： 浙江省杭州市 吉日嘎拉 手机：13858163011 电子邮件：JiRiGaLa_Bao@Hotmail.com 对软件进行注册。";
        public string TimeFormat = "HH:mm:ss";               // 时间格式

        public const string CURRENT_LOGIN_TO = "LoginTo";
        public const string COMPANY_NAME = "Jirisoft";
        public const string CURRENT_USERNAME = "CurrentUsername";
        public const string CURRENT_PASSWORD = "CurrentPassword";

        // 客户信息配置
        public const string CUSTOMER_COMPANYNAME = "CustomerCompanyName";
        public const string CONFIGURATION_FROM = "ConfigurationFrom";
        public const string SOFT_NAME = "SoftName";
        public const string SOFT_FULLNAME = "SoftFullName";
        public const string RUN_MODE = "RunMode";
        public const string ROOT_MENU_ID = "RootMenuID";
        public const string CURRENT_LANGUAGE = "CurrentLanguage";
        public const string VERSION = "Version";


        // 这里是服务器设置项
        public const string COMMON_WEBSERVICE = "CommonWebService";
        public const string WEBSERVICE = "WebService";

        public const string FILE_WEBSERVICE = "FileWebService";
        public const string WORKREPORT_WEBSERVICE = "WorkReportWebService";

        public const string WEBSERVICE_USERNAME = "WebServiceUsername";
        public const string WEBSERVICE_PASSWORD = "WebServicePassword";

        public const string USE_PERMISSIONS_COPE = "UsePermissionScope";          // 启用分级管理范围权限设置
        public const string USE_LICENSED_PERMISSION = "UseLicensedPermission";  // 启用逐级授权

        public const string SERVICE_FACTORY = "ServiceFactory";
        public const string SERVICE_PATH = "ServicePath";
        public const string DBHELPER_CLASSNAME = "DbHelperClass";
        public const string DBHELPER_ASSMELY = "DbHelperAssmely";
        public const string RECORD_LOG = "RecordLog";

        // 登录窗体
        public const string LOGIN_ASSEMBLY = "LoginAssembly";
        public const string LOGIN_FORM = "LoginForm";
        public const string MAIN_FORM = "MainForm";

        public const string LOAD_USER = "LoadUser";
        public const string ALLOW_USER_REGISTER = "AllowUserRegister";

        // 数据库连接
        public const string USERCENTER_DBCONNECTION = "UserCenterDbConnection";
        public const string BUSINESS_DBCONNECTION = "BusinessDbConnection";

        public const string DATABASE_TYPE = "DataBaseType";
        public const string SERVER_NAME = "ServerName";
        public const string DATABASE = "DataBase";
        public const string TRUST_LINK = "TrustLink";
        public const string USER_NAME = "Username";
        public const string PASSWORD = "Password";
        public const string MAX_POOL_SIZE = "MaxPoolSize";
        public const string MIN_POOL_SIZE = "MinPoolSize";
        public const string REGISTER_KEY = "RegisterKey";

        #region public BaseConfiguration()
        /// <summary>
        /// 构造方法
        /// </summary>
        public BaseConfiguration()
        {
        }
        #endregion

        #region public BaseConfiguration(string softName)
        /// <summary>
        /// 设定当前软件ID
        /// </summary>
        /// <param name="softName">当前软件ID</param>
        public BaseConfiguration(string softName)
        {
            this.SoftName = softName;
        }
        #endregion

        #region public DataBaseType GetDataBaseType(string dataBase)
        /// <summary>
        /// 数据库连接的类型判断
        /// </summary>
        /// <param name="dataBase">数据库类型</param>
        /// <returns>数据库类型</returns>
        public DataBaseType GetDataBaseType(string dataBase)
        {
            DataBaseType returnValue = DataBaseType.Sqlserver;
            foreach (DataBaseType dataBaseType in Enum.GetValues(typeof(DataBaseType)))
            {
                if (dataBaseType.ToString().Equals(dataBase))
                {
                    returnValue = dataBaseType;
                    break;
                }
            }
            return returnValue;
        }
        #endregion

        #region public ConfigurationCategory GetConfiguration(string configuration)
        /// <summary>
        /// 配置信息的类型判断
        /// </summary>
        /// <param name="configuration">配置信息类型</param>
        /// <returns>配置信息类型</returns>
        public ConfigurationCategory GetConfiguration(string configuration)
        {
            ConfigurationCategory returnValue = ConfigurationCategory.Configuration;
            foreach (ConfigurationCategory configurationCategory in Enum.GetValues(typeof(ConfigurationCategory)))
            {
                if (configurationCategory.ToString().Equals(configuration))
                {
                    returnValue = configurationCategory;
                    break;
                }
            }
            return returnValue;
        }
        #endregion

        #region public GetRunMode(string runMode)
        /// <summary>
        /// 运行模式配置
        /// </summary>
        /// <param name="runMode">运行模式</param>
        /// <returns>配置信息类型</returns>
        public RunMode GetRunMode(string runMode)
        {
            RunMode returnValue = RunMode.Local;
            foreach (RunMode mode in Enum.GetValues(typeof(RunMode)))
            {
                if (mode.ToString().Equals(runMode))
                {
                    returnValue = mode;
                    break;
                }
            }
            return returnValue;
        }
        #endregion


        #region public string OracleConnection 获得 Oracle 数据库连接
        /// <summary>
        /// 获得 Oracle 数据库连接
        /// </summary>
        public string OracleConnection
        {
            get
            {
                if (!String.IsNullOrEmpty(this.UserCenterDbConnection))
                {
                    return this.UserCenterDbConnection;
                }
                return String.Format(CultureInfo.CurrentCulture, "Data Source={0};Persist Security Info=no;User ID={1};Password={2}", this.ServerName, this.Username, this.Password);
            }
        }
        #endregion

        #region public string SqlConnection 获得 Sql Server 数据库连接
        /// <summary>
        /// 获得 Sql Server 数据库连接
        /// </summary>
        public string SqlConnection
        {
            get
            {
                if (!String.IsNullOrEmpty(this.UserCenterDbConnection))
                {
                    return this.UserCenterDbConnection;
                }
                if (this.TrustLink)
                {
                    return String.Format(CultureInfo.CurrentCulture, "Server={0};Database={1};Integrated Security=True", this.ServerName, this.DataBase);
                }
                else
                {
                    return String.Format(CultureInfo.CurrentCulture, "Server={0};Database={1};Uid={2};Pwd={3};", this.ServerName, this.DataBase, this.Username, this.Password);
                }
            }
        }
        #endregion

        #region public string MySqlConnection 获得 MySql 数据库连接
        /// <summary>
        /// 获得 MySql 数据库连接
        /// </summary>
        public string MySqlConnection
        {
            get
            {
                if (!String.IsNullOrEmpty(this.UserCenterDbConnection))
                {
                    return this.UserCenterDbConnection;
                }
                return String.Format(CultureInfo.CurrentCulture, "server={0};uid={1};password={2};database={3};pooling=false", this.ServerName, this.Username, this.Password, this.DataBase);
            }
        }
        #endregion

        #region public string OleDbConnection 获得 OleDb 数据库连接
        /// <summary>
        /// 获得 OleDb 数据库连接
        /// </summary>
        public string OleDbConnection
        {
            get
            {
                if (!String.IsNullOrEmpty(this.UserCenterDbConnection))
                {
                    return this.UserCenterDbConnection;
                }
                return this.GetOleDbConnection();
            }
        }
        #endregion


        #region public string GetOleDbConnection()
        /// <summary>
        /// 获得数据库连接
        /// </summary>
        /// <returns>数据库连接</returns>
        public string GetOleDbConnection()
        {
            return this.GetOleDbConnection(this.DataBaseType, this.DataBase, this.Username, this.Password, this.ServerName, this.TrustLink);
        }
        #endregion

        #region public string GetOleDbConnection(string dataBaseType, string dataBase, string userName, string password, string workstation, bool trustLink)
        /// <summary>
        /// 获得数据库连接
        /// </summary>
        /// <param name="dataBaseType">数据库类别</param>
        /// <param name="dataBase">数据库名</param>
        /// <param name="userName">用户名</param>
        /// <param name="password">密码</param>
        /// <param name="workstation">主机</param>
        /// <param name="trustLink">信任的连接</param>
        /// <returns>是否连接成功</returns>
        public string GetOleDbConnection(DataBaseType dataBaseType, string dataBase, string userName, string password, string workstation, bool trustLink)
        {
            string returnValue = string.Empty;
            switch (dataBaseType)
            {
                case DataBaseType.Access:
                    if (dataBase.IndexOf(":") < 0)
                    {
                        dataBase = this.StartupPath + dataBase;
                    }
                    returnValue = String.Format(CultureInfo.CurrentCulture, "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\"{0}\";User Id={1};jet OleDB:Database Password={2}", dataBase, userName, password);
                    break;
                case DataBaseType.Sqlserver:
                    // 信任的连接与不信任的连接的差距
                    if (trustLink)
                    {
                        returnValue = String.Format(CultureInfo.CurrentCulture, "Provider=SQLOLEDB;Data Source={0};Initial Catalog={1};Integrated Security=SSPI;Max Pool Size={2}; Min Pool Size={3}", workstation, dataBase, MaxPoolSize, MinPoolSize);
                    }
                    else
                    {
                        returnValue = String.Format(CultureInfo.CurrentCulture, "Provider=SQLOLEDB;Data Source={0};Initial Catalog={1};User ID={2};Password={3};Max Pool Size={4}; Min Pool Size={5}", workstation, dataBase, userName, password, MaxPoolSize, MinPoolSize);
                    }
                    break;
                case DataBaseType.Oracle:
                    if (!trustLink)
                    {
                        // 需要上传文件时必须用 Provider=OraOLEDB.Oracle.1
                        returnValue = String.Format(CultureInfo.CurrentCulture, "Provider=OraOLEDB.Oracle.1;Data Source={0};User Id={1};Password={2};", dataBase, userName, password);
                        // returnValue = String.Format(CultureInfo.CurrentCulture, "Provider=msdaora;Data Source={0};User Id={1};Password={2};", dataBase, userName, password);
                    }
                    break;
            }
            return returnValue;
        }
        #endregion

        #region public void GetSetting()
        /// <summary>
        /// 读取配置信息
        /// </summary>
        public void GetSetting()
        {
            if (this.ConfigurationFrom == ConfigurationCategory.RegistryKey)
            {
                RegistryHelper.GetConfig(BaseConfiguration.Instance);
            }
            if (this.ConfigurationFrom == ConfigurationCategory.Configuration)
            {
                ConfigurationHelper.GetConfig(BaseConfiguration.Instance);
            }
            if (this.ConfigurationFrom == ConfigurationCategory.UserConfig)
            {
                ConfigHelper.GetConfig(BaseConfiguration.Instance);
            }
            // 获取数据库连接字符串
            // this.ConnectionString = this.GetOleDbConnection();
        }
        #endregion
    }
}